package com.xinhe.cn.cpbox.utils;

import cn.hutool.core.lang.ObjectId;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Objects;
import java.util.UUID;

/**
 * @author LHB
 * @date 2021/10/09 10:55
 */
@Component
public class TencenCloudUtil {
    @Value("${wx.cloud.SECRET_ID}")
    private String SECRET_ID;
    @Value("${wx.cloud.SECRET_KEY}")
    private String SECRET_KEY;
    @Value("${wx.cloud.OBJCET_ADRESS}/")    // 注意结尾有'/'
    private String OBJCET_ADRESS;
    @Value("${wx.cloud.BUCKET_NAME}")
    private String BUCKET_NAME;
    @Value("${wx.cloud.REGION_NAME}")
    private String REGION_NAME;

    private COSClient COS_CLIENT;

    public COSClient getCOSClient() {
        if (Objects.isNull(COS_CLIENT)) {
            COSCredentials cred = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);
            Region region = new Region(REGION_NAME);
            ClientConfig clientConfig = new ClientConfig(region);
            COS_CLIENT = new COSClient(cred, clientConfig);
        }
        return COS_CLIENT;
    }

    public String upload(File file) {
        String key = "images/" + UUID.randomUUID() + file.getName().substring(file.getName().lastIndexOf("."));
        PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, key, file);
        PutObjectResult putObjectResult = getCOSClient().putObject(putObjectRequest);
        boolean delete = file.delete();
        return OBJCET_ADRESS + key;
    }

    public void deleteImage(String image) {
        image = image.substring(image.lastIndexOf("images"), image.length());
        getCOSClient().deleteObject(BUCKET_NAME, image);
    }

    public String uploadByPost(File file) {
        String key = "images/" + ObjectId.next() + file.getName().substring(file.getName().lastIndexOf("."));
        PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, key, file);
        PutObjectResult putObjectResult = getCOSClient().putObject(putObjectRequest);
        boolean delete = file.delete();
        return OBJCET_ADRESS + key;
    }
}
